﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using DXTools.UI.Core.Dialogs;
using DXTools.Core;

namespace DXTools.UI.Shell
{
    public partial class App : Application
    {

        public App()
        {
            try
            {
                this.Startup += this.Application_Startup;
                this.Exit += this.Application_Exit;
                this.UnhandledException += this.Application_UnhandledException;

                InitializeComponent();
            }
            catch (Exception ex)
            {
                ReportExceptionToDOM(ex);
            }
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                WebClient webClient = new WebClient();
                webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
                webClient.OpenReadAsync(new System.Uri(GetModulesCatalogUrl(), System.UriKind.Absolute));
            }
            catch (Exception ex)
            {
                ReportExceptionToDOM(ex);
            }

        }

        private string GetModulesCatalogUrl()
        {

                string baseUrl = DXTools.Core.ClientScript.GetServerUrl();

                if (App.Current.Host.InitParams.Keys.Contains("Testing"))
                    return string.Format("{0}://{1}:{2}/", App.Current.Host.Source.Scheme, App.Current.Host.Source.Host, App.Current.Host.Source.Port) + "ClientBin/ModuleCatalog.xaml.xml";
                else
                {

                    return baseUrl + "/WebResources/dxtools_/SL/ModuleCatalog.xaml.xml";
                }
            
                
        }

        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    Bootstrapper bootstrapper = new Bootstrapper(e.Result);
                    bootstrapper.Run();
                }
                else
                {
                    throw new Exception("Module Catalog couldn't be downloaded. Message: " + e.Error.Message, e.Error);
                }
            }
            catch (Exception ex)
            {
               ReportExceptionToDOM(ex);
            }
        }

        private void Application_Exit(object sender, EventArgs e)
        {
            
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            //if (!System.Diagnostics.Debugger.IsAttached)
            //{

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
              
            //}
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
               
                string errorMsg = ConvertToString(e.ExceptionObject); // e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                //errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                ErrorDialog errorDialog = new ErrorDialog();
                errorDialog.Message = errorMsg;
                errorDialog.Show();

                //System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception ex)
            {
                ErrorDialog errorDialog = new ErrorDialog();
                errorDialog.Message = ex.Message;
                errorDialog.Show();
            }
        }

        private void ReportExceptionToDOM(Exception e)
        {
            try
            {

                string errorMsg = ConvertToString(e); // e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                //errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                ErrorDialog errorDialog = new ErrorDialog();
                errorDialog.Message = errorMsg;
                errorDialog.Show();

                //System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception ex)
            {
                ErrorDialog errorDialog = new ErrorDialog();
                errorDialog.Message = ex.Message;
                errorDialog.Show();
            }
        }

        private string ConvertToString(Exception exception)
        {
            string prefix = "";

            StringBuilder sb = new StringBuilder();
            while (null != exception)
            {
                sb.Append(prefix);
                sb.AppendLine(String.IsNullOrEmpty(exception.Message) == false ? exception.Message : String.Empty);
                sb.AppendLine(String.IsNullOrEmpty(exception.StackTrace) == false ? exception.StackTrace : String.Empty);

                prefix = "Inner Exception: ";
                exception = exception.InnerException;
            }

            return sb.ToString();
        }
    }
}
